from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware  # 安装 pip install fastapi uvicorn python-multipart
from fastapi.responses import FileResponse
from pydantic import BaseModel
from ai_module import SmartBikeRAGSystem  # 我们将重构您的代码

app = FastAPI(title="智能单车治理系统", version="1.0.0")

# 配置CORS，允许前端访问
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该设置具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 请求/响应模型
class QuestionRequest(BaseModel):
    question: str
    chat_id: str


class QuestionResponse(BaseModel):
    answer: str
    source_documents: list
    processing_time: float


# 全局RAG系统实例
rag_system = None


@app.on_event("startup")
async def startup_event():
    """启动时初始化RAG系统"""
    global rag_system
    try:
        rag_system = SmartBikeRAGSystem()
        rag_system.initialize_system()
        print("✅ RAG系统初始化完成")
    except Exception as e:
        print(f"❌ RAG系统初始化失败: {e}")
        raise


@app.get("/")
async def read_root():
    return {"message": "智能单车治理系统 API 服务运行中"}


@app.post("/ask", response_model=QuestionResponse)
async def ask_question(request: QuestionRequest):
    """问答接口"""
    if rag_system is None:
        raise HTTPException(status_code=503, detail="系统未初始化完成")

    if not request.question.strip():
        raise HTTPException(status_code=400, detail="问题不能为空")

    try:
        result = rag_system.ask_question(request.question, request.chat_id)
        return QuestionResponse(**result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理问题时出错: {str(e)}")


@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "rag_initialized": rag_system is not None,
        "model": rag_system.MODEL_NAME if rag_system else None
    }


# 提供前端页面
@app.get("/ui")
async def get_ui():
    return FileResponse("frontend.html")


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
